import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'
import { dirname, join, resolve } from 'path'

export function readJsonFile(filePath: string): any {
  try {
    const content = readFileSync(filePath, 'utf-8')
    return JSON.parse(content)
  } catch (error) {
    throw new Error(`Failed to read JSON file ${filePath}: ${error}`)
  }
}

export function writeJsonFile(filePath: string, data: any): void {
  try {
    const content = JSON.stringify(data, null, 2)
    ensureDirectoryExists(dirname(filePath))
    writeFileSync(filePath, content, 'utf-8')
  } catch (error) {
    throw new Error(`Failed to write JSON file ${filePath}: ${error}`)
  }
}

export function readTextFile(filePath: string): string {
  try {
    return readFileSync(filePath, 'utf-8')
  } catch (error) {
    throw new Error(`Failed to read text file ${filePath}: ${error}`)
  }
}

export function writeTextFile(filePath: string, content: string): void {
  try {
    ensureDirectoryExists(dirname(filePath))
    writeFileSync(filePath, content, 'utf-8')
  } catch (error) {
    throw new Error(`Failed to write text file ${filePath}: ${error}`)
  }
}

export function fileExists(filePath: string): boolean {
  return existsSync(filePath)
}

export function ensureDirectoryExists(dirPath: string): void {
  if (!existsSync(dirPath)) {
    mkdirSync(dirPath, { recursive: true })
  }
}

export function resolvePath(...paths: string[]): string {
  return resolve(join(...paths))
}

export function getCurrentWorkingDirectory(): string {
  return process.cwd()
}
